import {api1} from "@/common/api/request";
import {Toast} from "mint-ui";
export default {
  state:{
    list:[],
    selectedList:[],
  },
  getters:{
    //计算总价和数量
    total(state){
      //初始化结果
      let total = {
        price:0,
        num:0
      }
      state.list.forEach(v=>{
        if(v.checked){
          total.price += v.goods_num * v.goods_price
          total.num += v.goods_num
        }
      })
      return total
    }
  },
  mutations:{
    //请求到的数据进行赋值 state.list
    initGetData(state,cartArr){
      state.list = cartArr
      state.list.forEach( v=> {
        state.selectedList.push(v.id)
      })
    },
    deleteGoods(state,id){
      state.list = state.list.filter(v=>{
        return v.id != id
      })
    },
    selectItem(state,index){
      let id = state.list[index].id
      let i = state.selectedList.indexOf(id)
      if( i > -1 ){
        //选中
        state.list[index].checked = false
        return state.selectedList.splice(i,1)
      }else {
        //如果没有选中
        state.list[index].checked = true
        state.selectedList.push(id)
      }
    }
  },
  actions:{
    deleteGoodsFn({commit},id){
      api1({
        url: '/api/deleteCart',
        method: 'POST',
        headers:{
          token:true
        },
        data:{
          id
        }
      }).then(res => {
        if(res.success){
          commit('deleteGoods',id)
          Toast(res.msg)
        }
      })
    }
  }
}